package menu;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

/**
 * 战绩界面
 */

public class RecordMenu {

    public RecordMenu(){
        int sum = countSum();
        double avg = countAvg();
        System.out.println("---------------------------");
        System.out.printf("你的总场数是: %d, 你的胜率为: %.2f", sum, avg * 100);
        System.out.println("%");
        System.out.println("---------------------------");
    }

    public void start(){
        Scanner scanner = new Scanner(System.in);
        int input = 0;
        do{
            System.out.print("输入1返回菜单:>");
            input = scanner.nextInt();
            switch (input){
                case 1:
                    new StartMenu().start();
                    break;
                case 0:
                    System.out.println("游戏结束");
                    System.exit(0);
                default:
                    System.out.println("输入错误, 请重新输入!");
            }
        }while (true);
    }

    private int countSum(){
        int len = 0;
        try (Reader reader = new FileReader("./test.txt")) {
            // 按照字符来读.
            while (true) {
                char[] buffer = new char[1024];
                len = reader.read(buffer);
                if (len == -1){
                    break;
                }
                return len;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private double countAvg(){
        double avg = 0;
        try (Reader reader = new FileReader("./test.txt")) {
            // 按照字符来读.
            char[] buffer = new char[1024];
            int len = 0;
            double cnt = 0;
            while (true) {
                len = reader.read(buffer);
                if (len == -1){
                    break;
                }
                for (int i = 0; i < len; i++){
                    int k = Integer.parseInt(String.valueOf(buffer[i]));
                    if (k == 1){
                        cnt++;
                    }
                }
                avg = cnt / len;
                return avg;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
